package com.mbyte.easy.admin.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mbyte.easy.admin.Vo.DimensionVO;
import com.mbyte.easy.admin.Vo.ExamVO;
import com.mbyte.easy.admin.Vo.ExcelVO;
import com.mbyte.easy.admin.entity.Exam;
import com.mbyte.easy.admin.entity.ScoreInfo;
import com.mbyte.easy.admin.enums.DimensionEnums;
import com.mbyte.easy.admin.service.IExamService;
import com.mbyte.easy.admin.service.IScoreInfoService;
import com.mbyte.easy.common.controller.BaseController;
import com.mbyte.easy.common.web.AjaxResult;
import com.mbyte.easy.util.ExcelDataListener;
import com.mbyte.easy.util.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
* <p>
* 前端控制器
* </p>
* @author lp
* @since 2019-03-11
*/
@Slf4j
@Controller
@RequestMapping("/admin/scoreInfo")
public class ScoreInfoController extends BaseController  {

    private String prefix = "admin/scoreInfo/";

    @Autowired
    private IScoreInfoService scoreInfoService;

    @Autowired
    private IExamService examService;

    /**
     * 分析页面入口
     * @return
     */
    @RequestMapping("/data/analysis")
    public String dataAnalysis(Model model){

        // 获取考试场次
        List<Exam> examList = examService.list();
        if (CollectionUtils.isNotEmpty(examList)) {
            List<ExamVO> examVOList = examList.stream().map(index -> {
                ExamVO examVO = new ExamVO();
                examVO.setValue(index.getId());
                examVO.setName(index.getExamName());
                return examVO;
            }).collect(Collectors.toList());

            model.addAttribute("examList", examVOList);
        }

        // 获取分析的维度
        List<DimensionVO> dimensionVOList = Stream.of(DimensionEnums.values()).map(index -> {
            DimensionVO dimensionVO = new DimensionVO();
            dimensionVO.setCode(index.getCode());
            dimensionVO.setDesc(index.getDesc());
            return dimensionVO;
        }).collect(Collectors.toList());
        model.addAttribute("dimensionList", dimensionVOList);

        return prefix+"analysis";
    }

    /**
    * 查询列表
    *
    * @param model
    * @param pageNo
    * @param pageSize
    * @param scoreInfo
    * @return
    */
    @RequestMapping
    public String index(Model model,@RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,@RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize, String createTimeSpace, String updateTimeSpace, ScoreInfo scoreInfo) {
        Page<ScoreInfo> page = new Page<ScoreInfo>(pageNo, pageSize);
        QueryWrapper<ScoreInfo> queryWrapper = new QueryWrapper<ScoreInfo>();

        if(!ObjectUtils.isEmpty(scoreInfo.getGrade())) {
            queryWrapper = queryWrapper.like("grade",scoreInfo.getGrade());
         }
        if(!ObjectUtils.isEmpty(scoreInfo.getName())) {
            queryWrapper = queryWrapper.like("name",scoreInfo.getName());
         }
        if(!ObjectUtils.isEmpty(scoreInfo.getExamId())) {
            queryWrapper = queryWrapper.eq("exam_id",scoreInfo.getExamId());
         }
        if(!ObjectUtils.isEmpty(scoreInfo.getChinese())) {
            queryWrapper = queryWrapper.eq("chinese",scoreInfo.getChinese());
         }
        if(!ObjectUtils.isEmpty(scoreInfo.getMath())) {
            queryWrapper = queryWrapper.eq("math",scoreInfo.getMath());
         }
        if(!ObjectUtils.isEmpty(scoreInfo.getEnglish())) {
            queryWrapper = queryWrapper.eq("english",scoreInfo.getEnglish());
         }
        if(!ObjectUtils.isEmpty(scoreInfo.getWenSum())) {
            queryWrapper = queryWrapper.eq("wen_sum",scoreInfo.getWenSum());
         }
        if(!ObjectUtils.isEmpty(scoreInfo.getLiSum())) {
            queryWrapper = queryWrapper.eq("li_sum",scoreInfo.getLiSum());
         }

        // 获取考试场次
        List<Exam> examList = examService.list();

        IPage<ScoreInfo> pageInfo = scoreInfoService.page(page, queryWrapper);
        model.addAttribute("searchInfo", scoreInfo);
        model.addAttribute("examList", examList);
        model.addAttribute("pageInfo", new PageInfo(pageInfo));
        return prefix+"list";
    }

    /**
    * 添加跳转页面
    * @return
    */
    @GetMapping("addBefore")
    public String addBefore(Model model){
        // 获取考试场次
        List<Exam> examList = examService.list();
        model.addAttribute("examList", examList);
        return prefix+"add";
    }
    /**
    * 添加
    * @param scoreInfo
    * @return
    */
    @PostMapping("add")
    @ResponseBody
    public AjaxResult add(ScoreInfo scoreInfo){
        return toAjax(scoreInfoService.save(scoreInfo));
    }
    /**
    * 添加跳转页面
    * @return
    */
    @GetMapping("editBefore/{id}")
    public String editBefore(Model model,@PathVariable("id")Long id){
        model.addAttribute("scoreInfo",scoreInfoService.getById(id));
        List<Exam> examList = examService.list();
        model.addAttribute("examList", examList);
        return prefix+"edit";
    }
    /**
    * 添加
    * @param scoreInfo
    * @return
    */
    @PostMapping("edit")
    @ResponseBody
    public AjaxResult edit(ScoreInfo scoreInfo){
        return toAjax(scoreInfoService.updateById(scoreInfo));
    }
    /**
    * 删除
    * @param id
    * @return
    */
    @GetMapping("delete/{id}")
    @ResponseBody
    public AjaxResult delete(@PathVariable("id") Long id){
        return toAjax(scoreInfoService.removeById(id));
    }
    /**
    * 批量删除
    * @param ids
    * @return
    */
    @PostMapping("deleteAll")
    @ResponseBody
    public AjaxResult deleteAll(@RequestBody List<Long> ids){
        return toAjax(scoreInfoService.removeByIds(ids));
    }


    /**
     * excel导入
     * @param fileupload
     * @return
     */
    @PostMapping("uploadExcel")
    @ResponseBody
    public AjaxResult assistUploadImg(MultipartFile fileupload) {
        try {
            if (fileupload.isEmpty() || StringUtils.isEmpty(fileupload.getOriginalFilename())) {
                return AjaxResult.error("上传文件不可为空");
            }
            // 获取文件名称
            String examName = fileupload.getOriginalFilename().substring(0, fileupload.getOriginalFilename().lastIndexOf("."));

            // 查询场次是否存在
            List<Exam> examList = examService.list(new LambdaQueryWrapper<Exam>().eq(Exam::getExamName, examName));
            if (CollectionUtils.isNotEmpty(examList)){
                return AjaxResult.success("考试场次已创建，请不要反复创建");
            }

            EasyExcel.read(fileupload.getInputStream(), ExcelVO.class, new ExcelDataListener(scoreInfoService, examService, examName))
                    .sheet()
                    .headRowNumber(2)
                    .doRead();
            return AjaxResult.success("导入成功");
        } catch (Exception e) {
            log.error("导入出错:", e);
            return AjaxResult.error("导入失败!");
        }
    }
}

